package org.wcf.util.xml;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;

/**
 * @author wuchaofei
 * @date 2016/3/29
 */
public class Dom4jFormatter implements Formatter {
    public static void main(String[] args) throws IOException {
        formatXmlFile("E:\\le\\CodeGenUtil\\out\\mybatis\\Product.xml");
    }

    public static void formatXmlFile(String src){
        formatXmlFile(src,src);
    }

    public static void formatXmlFile(String src,String target){
        String xml = null;
        if(target==null || target.length()==0){
            target=src;
        }
        try {
            xml = fileReaderImpl(src);
            xml = formatString(xml);
            fileWriterImpl(target,xml);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String fileReaderImpl(String src) throws IOException {
        BufferedReader bufferedReader = null;
        StringBuilder sb =new StringBuilder();
        try{
            bufferedReader = new BufferedReader(new FileReader(src));
            String var1;
            while ((var1 = bufferedReader.readLine()) != null) {
                sb.append(var1);
                sb.append("\r\n");
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }
        return sb.toString();
    }

    public static void fileWriterImpl(String target,String context) throws IOException {
        File dest = new File(target);
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(dest));
            writer.write(context);
            writer.flush();
        }finally {
            if(writer!=null){
                writer.close();
            }
        }
    }

    /**
     * 格式化xml文本
     * @param inputXML
     * @return
     * @throws Exception
     */
    public static String formatString(String inputXML) throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new StringReader(inputXML));
        String requestXML = null;
        XMLWriter writer = null;
        if (document != null) {
            try {
                StringWriter stringWriter = new StringWriter();
                OutputFormat format = new OutputFormat(" ", true);
                writer = new XMLWriter(stringWriter, format);
                writer.write(document);
                writer.flush();
                requestXML = stringWriter.getBuffer().toString();
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
        return requestXML;
    }
}
